<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useSearchStore } from '@/store'
import { storeToRefs } from 'pinia'

const router = useRouter()
const searchStore = useSearchStore()

const searchCtx = ref('')// 搜索框内容
const { searchHistory } = storeToRefs(searchStore) // 搜索历史

// 搜索
const goSearch = (key) => {
  if (key === '') return showToast('搜索内容不能为空哦')

  const index = searchHistory.value.indexOf(key)
  if (index !== -1) { // index !== -1表示在数组中存在
    // 如果存在，则删除
    searchHistory.value.splice(index, 1)
  }
  searchStore.addSearchHistory(key) // 添加搜索历史

  searchCtx.value = '' // 清空搜索历史栏

  router.push(`/search-list?search=${key}`)
}

const clear = () => {
  searchHistory.value = []
  showToast('搜索历史已清空')
}

onMounted(() => {
  searchStore.getSearchHistory()
})

</script>

<template>
  <div class="search">
    <van-nav-bar title="商品搜索" left-arrow @click-left="router.replace('/home')"/>

    <van-search show-action placeholder="请输入搜索关键词" clearable v-model.trim="searchCtx">
      <template #action>
        <div @click="goSearch(searchCtx)">搜索</div>
      </template>
    </van-search>

    <!-- 搜索历史 -->
    <div class="search-history" v-if="searchHistory.length > 0">
      <div class="title">
        <span>最近搜索</span>
        <van-icon @click="clear" name="delete-o" size="16"/>
      </div>
      <div class="list">
        <div
          class="list-item"
          @click="goSearch(item)"
          v-for="item in searchHistory"
          :key="item">{{ item }}
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.search {
  .searchBtn {
    background-color: #fa2209;
    color: #fff;
  }

  ::v-deep .van-search__action {
    background-color: #c21401;
    color: #fff;
    padding: 0 20px;
    border-radius: 0 5px 5px 0;
    margin-right: 10px;
  }

  ::v-deep .van-icon-arrow-left {
    color: #333;
  }

  .title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
  }

  .list {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 0 10px;
    gap: 5%;
  }

  .list-item {
    width: 30%;
    text-align: center;
    padding: 7px;
    line-height: 15px;
    border-radius: 50px;
    background: #fff;
    font-size: 13px;
    border: 1px solid #efefef;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-bottom: 10px;
  }
}
</style>

<script>
export default {
  name: 'SearchIndex'
}
</script>
